package tasks;

import javax.swing.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedWriter;
import java.util.concurrent.locks.ReentrantLock;

public class TaskOneKeyListener extends JFrame implements KeyListener {
    double[] speed = {0.0, 0.0, 0.0};
    ReentrantLock speedLock = new ReentrantLock();
    boolean abnormal = false;
    ReentrantLock abnormalLock = new ReentrantLock();
    BufferedWriter bw = null;
    ReentrantLock bwLock = new ReentrantLock();
    boolean end = false;
    ReentrantLock endLock = new ReentrantLock();

    Thread abnormalThread = null;
    long startTime = 0;


    // 构造函数，设置基本的窗口属性和添加KeyListener
    public TaskOneKeyListener() {
        this.setTitle("KeyListener Example");
        this.setSize(300, 200);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public void start() {
        this.addKeyListener(this); // 添加键盘监听器
        this.setVisible(true);
        abnormalThread = new Thread(() -> {
            while (true) {
                endLock.lock();
                boolean end = this.end;
                endLock.unlock();
                if (end) {
                    break;
                }
                try {
                    Thread.sleep((long) (2000 + Math.random() * 2000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                boolean abnormal = Math.random() > 0.5; // 50%概率使左右速度反向
                abnormalLock.lock();
                this.abnormal = abnormal;
                abnormalLock.unlock();
            }
        });
        startTime = System.currentTimeMillis();
        abnormalThread.start();
    }

    public void end() {
        endLock.lock();
        end = true;
        endLock.unlock();
        try {
            abnormalThread.join();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        SwingUtilities.invokeLater(() -> {
            setVisible(false); // 关闭窗口
            dispose(); // 释放资源
        });
    }

    public double[] getSpeed() {
        speedLock.lock();
        double[] ret = speed.clone();
        speedLock.unlock();
        abnormalLock.lock();
        ret[2] = abnormal ? -ret[2] : ret[2]; // 50%概率使左右速度反向
        abnormalLock.unlock();
        return ret;
    }

    // 主函数，用于实例化窗口
    public static void main(String[] args) {
        new TaskOneKeyListener();
    }

    public static double xys = 0.2; // x,y轴速度常量
    public static double zs = 1.0; // z轴速度常量
    // 当键盘键被按下时调用
    @Override
    public void keyPressed(KeyEvent e) {
//        System.out.println("Key Pressed: " + KeyEvent.getKeyText(e.getKeyCode()));
        switch (e.getKeyCode()) {
            case KeyEvent.VK_UP:
                speedLock.lock();
                speed[0] = xys;
                speedLock.unlock();
                break;
            case KeyEvent.VK_DOWN:
                speedLock.lock();
                speed[0] = -xys;
                speedLock.unlock();
                break;
            case KeyEvent.VK_LEFT:
                speedLock.lock();
//                speed[1] = -xys;
                speed[2] = -zs;
                speedLock.unlock();
                break;
            case KeyEvent.VK_RIGHT:
                speedLock.lock();
//                speed[1] = xys;
                speed[2] = zs;
                speedLock.unlock();
                break;
        }
    }

    // 当键盘键被释放时调用
    @Override
    public void keyReleased(KeyEvent e) {
//        System.out.println("Key Released: " + KeyEvent.getKeyText(e.getKeyCode()));
        switch (e.getKeyCode()) {
            case KeyEvent.VK_UP:
            case KeyEvent.VK_DOWN:
                speedLock.lock();
                speed[0] = 0.0;
                speedLock.unlock();
                break;
            case KeyEvent.VK_LEFT:
            case KeyEvent.VK_RIGHT:
                speedLock.lock();
//                speed[1] = 0.0;
                speed[2] = 0.0;
                speedLock.unlock();
                break;
        }
    }

    // 当键盘键被敲击（按下再释放）时调用
    @Override
    public void keyTyped(KeyEvent e) {
        // keyTyped通常用于处理字符输入
    }
}
